package com.shujia.service;

import com.shujia.entity.Dept;
import com.shujia.utils.MySqlTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class DeptServiceImpl implements DeptService{
    private Connection conn = MySqlTool.getConnection();

    //使用Springboot提供给我们的一个JDBC类
    //使用@Autowired将对象注入进来
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public List<Dept> getAllDeptInfo() {
        ArrayList<Dept> depts = new ArrayList<>();

        try {

            PreparedStatement prepareStatement = conn.prepareStatement("select deptno,dname,loc from dept");
            ResultSet resultSet = prepareStatement.executeQuery();
            while (resultSet.next()){

                int deptno = resultSet.getInt(1);
                String dname = resultSet.getString(2);
                String loc = resultSet.getString(3);
                Dept dept = new Dept(deptno,dname,loc);
                depts.add(dept);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return depts;
    }

    @Override
    public Dept getDeptByNo(int deptNo) {
        String sql = "select * from dept where deptno=?";
        Map<String, Object> map = jdbcTemplate.queryForMap(sql, deptNo);
        Dept dept = new Dept();

        dept.setDeptno((int)(map.get("deptno")));
        dept.setDname(map.get("dname").toString());
        dept.setLoc(map.get("loc").toString());

        return dept;
    }

    @Override
    public String saveDept(Dept dept) {
        String sql = "insert into dept(deptno,dname,loc) values(?,?,?)";

        int i = jdbcTemplate.update(sql, new Object[]{dept.getDeptno(),
                dept.getDname(),
                dept.getLoc(),}, new int[]{Types.INTEGER, Types.VARCHAR, Types.VARCHAR});

        return i==1?"数据保存成功！！":"数据保存失败！！";
    }
}
